package com.mjp.zookeeper.watcher;

import com.mjp.zookeeper.entity.MyConf;
import org.apache.zookeeper.*;
import org.apache.zookeeper.data.Stat;

import java.util.concurrent.CountDownLatch;

public class WatchCallback implements Watcher, AsyncCallback.StatCallback, AsyncCallback.DataCallback {
    private ZooKeeper zk;

    private MyConf myConf;

    private String url = "/test1";

    private CountDownLatch countDownLatch = new CountDownLatch(1);

    public WatchCallback(ZooKeeper zooKeeper,MyConf myConf) {
        this.zk = zooKeeper;
        this.myConf = myConf;
    }

    public void await() {
        zk.exists(url,this,this,"abc");
        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * watcher
     * @param event
     */
    @Override
    public void process(WatchedEvent event) {
        switch (event.getType()) {
            case None:
                break;
            case NodeCreated:
                System.out.println("node created");
                zk.getData(url,this,this,"abc");
                break;
            case NodeDeleted:
                System.out.println("node deleted");
                break;
            case NodeDataChanged:
                System.out.println("node data changed");
                zk.getData(url,this,this,"abc");
                break;
            case NodeChildrenChanged:
                break;
            case DataWatchRemoved:
                break;
            case ChildWatchRemoved:
                break;
            case PersistentWatchRemoved:
                break;
        }
    }

    /**
     * watch callback
     * @param rc
     * @param path
     * @param ctx
     * @param stat
     */
    @Override
    public void processResult(int rc, String path, Object ctx, Stat stat) {
        if(stat!=null){
            //如果stat不为空 代表节点已经存在了
            System.out.println("the node exists!");
            zk.getData(url,this,this,ctx);
        } else {
            //如果stat 为空，代表节点不存在 这个时候需要创建节点
            System.out.println("the node does't exist");
            try {
                zk.create(url,"appConf data".getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            } catch (KeeperException | InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * getDataCallback
     * @param rc
     * @param path
     * @param ctx
     * @param data
     * @param stat
     */
    @Override
    public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) {
        if(data!=null){
            myConf.setConf(new String(data));
            countDownLatch.countDown();
        }

    }
}
